﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信公众号系统</title>
    <style>
        /* 样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            border: 3px solid #07c160;
        }

        .content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            min-height: 400px;
        }

        .loading {
            text-align: center;
            padding: 40px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #07c160;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .btn {
            background: #07c160;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
            margin: 5px;
        }

            .btn:hover {
                background: #06ae56;
            }

        .btn-secondary {
            background: #6c757d;
        }

            .btn-secondary:hover {
                background: #5a6268;
            }

        .hidden {
            display: none;
        }

        .api-result {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            border-left: 4px solid #007bff;
            max-height: 300px;
            overflow-y: auto;
        }

        .error {
            border-left-color: #dc3545;
        }

        .success {
            border-left-color: #28a745;
        }

        .warning {
            border-left-color: #ffc107;
        }

        .session-timer {
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 8px 12px;
            border-radius: 5px;
            font-size: 12px;
            z-index: 1000;
        }

        .auth-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }

        .auth-content {
            background: white;
            padding: 40px;
            border-radius: 15px;
            text-align: center;
            max-width: 400px;
            width: 90%;
        }
    </style>
</head>
<body>
    <!-- 授权提示模态框 -->
    <div id="authModal" class="auth-modal">
        <div class="auth-content">
            <h3>需要微信授权</h3>
            <p>请授权以继续访问该页面</p>
            <div style="margin: 20px 0;">
                <button onclick="redirectToWeChatAuth()" class="btn">前往微信授权</button>
                <button onclick="hideAuthModal()" class="btn btn-secondary" style="margin-left: 10px;">取消</button>
            </div>
            <p style="font-size: 12px; color: #666;">授权后即可正常使用所有功能</p>
        </div>
    </div>

    <div id="sessionTimer" class="session-timer hidden">
        会话剩余: <span id="sessionTime">20:00</span>
    </div>

    <div class="container">
        <div class="header">
            <h1>微信公众号系统</h1>

            <button onclick="test()" class="btn">测试</button>

            

            <div id="userInfo" class="user-info hidden">
                <img id="userAvatar" class="avatar" src="" alt="用户头像" onerror="this.style.display='none'">
                <div>
                    <div id="userName" style="font-weight: bold;"></div>
                    <div style="font-size: 12px; color: #666;">已授权</div>
                </div>
                <button onclick="logout()" class="btn btn-secondary">退出</button>
            </div>
        </div>

        <div class="content">
            <div id="loading" class="loading">
                <div class="spinner"></div>
                <p>正在检查授权状态...</p>
            </div>

            <div id="mainContent" class="hidden">
                <h2>欢迎访问系统</h2>
                <p>这是一个受微信授权保护的页面，只有授权用户才能访问。</p>

                <div style="margin-top: 30px;">
                    <h3>功能测试</h3>
                    <button onclick="getUserInfo()" class="btn">获取用户信息</button>
                    <button onclick="getProtectedData()" class="btn">获取受保护数据</button>
                    <button onclick="refreshSession()" class="btn">刷新会话</button>
                    <button onclick="checkSession()" class="btn">检查会话状态</button>
                </div>

                <div id="apiResult" class="api-result hidden"></div>
            </div>
        </div>
    </div>

    <script>
        class AuthManager {
            constructor() {
                this.apiBaseUrl = '/api';
                this.isChecking = false;
                this.sessionTimer = null;
                this.sessionExpiry = 20 * 60 * 1000; // 20分钟
                this.pendingAuthUrl = null;
            }

            // 初始化检查
            async init() {
                await this.checkAuthStatus();
                //this.startSessionTimer();

                //// 定期检查会话状态（每2分钟）
                //setInterval(() => this.checkAuthStatus(), 2 * 60 * 1000);
            }

            // 检查认证状态
            async checkAuthStatus() {

                console.log("1=============");
                if (this.isChecking) return;
                this.isChecking = true;

                try {
                    const response = await fetch(`${this.apiBaseUrl}/auth/check-session`, {
                        credentials: 'include',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        }
                    });

                    console.log("2=============");


                    if (!response.ok)
                    {
                        console.log("21=============");

                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    console.log("22=============");

                    const result = await response.json();

                    console.log("3=============");

                    if (result.authenticated) {
                        this.showAuthenticatedUI(result.user);
                    } else {

                        console.log("==============");

                        // 未认证，显示授权提示
                        this.showAuthModal();
                    }
                } catch (error) {
                    console.error('检查认证状态失败:', error);
                    this.showApiResult('网络错误: ' + error.message, 'error');
                } finally {
                    this.isChecking = false;
                }
            }

            // 显示认证后的UI
            showAuthenticatedUI(userInfo) {
                document.getElementById('loading').classList.add('hidden');
                document.getElementById('mainContent').classList.remove('hidden');
                document.getElementById('userInfo').classList.remove('hidden');
                document.getElementById('sessionTimer').classList.remove('hidden');
                document.getElementById('authModal').classList.add('hidden');

                if (userInfo) {
                    document.getElementById('userName').textContent = userInfo.nickName || '微信用户';
                    if (userInfo.headImgUrl) {
                        document.getElementById('userAvatar').src = userInfo.headImgUrl;
                        document.getElementById('userAvatar').style.display = 'block';
                    }

                    // 存储用户信息到sessionStorage
                    sessionStorage.setItem('user_info', JSON.stringify(userInfo));
                }
            }

            // 显示授权模态框
            showAuthModal() {
                document.getElementById('loading').classList.add('hidden');
                document.getElementById('mainContent').classList.add('hidden');
                document.getElementById('userInfo').classList.add('hidden');
                document.getElementById('authModal').style.display = 'flex';
            }

            // 隐藏授权模态框
            hideAuthModal() {
                document.getElementById('authModal').style.display = 'none';
            }

            // 重定向到微信授权
            //async redirectToWeChatAuth() {
            //    try {


            //        // 获取授权URL
            //        const currentUrl = window.location.href;
            //        const redirectUri = `${window.location.origin}/auth-callback.html`;

            //        console.log("A1[" + currentUrl + "]");

            //        console.log("A12[" + redirectUri +"]");





            //        const response = await fetch(`${this.apiBaseUrl}/auth/auth-url?returnUrl=${encodeURIComponent(redirectUri)}`, {
            //            credentials: 'include'
            //        });

            //        console.log("A2=============");
            //        if (!response.ok)
            //        {
            //            console.log("A3=============");
            //            throw new Error(`获取授权URL失败: ${response.status}`);
            //        }

            //        console.log("A4=============");
            //        const result = await response.json();

            //        console.log("A5=============");
            //        if (result.url)
            //        {
            //            // 使用页面跳转而不是fetch
            //            window.location.href = result.url;
            //            console.log("result.url[" + result.url +"]");

            //        } else {
            //            this.showApiResult('获取授权URL失败', 'error');
            //        }
            //    } catch (error) {
            //        console.error('跳转授权失败:', error);
            //        this.showApiResult('跳转授权失败: ' + error.message, 'error');
            //    }
            //}

            // 启动会话计时器



            // 重定向到微信授权
            async redirectToWeChatAuth() {
                try {
                    // 重要：回调地址应该是 auth-callback.html，不是当前页面
                    const currentUrl = window.location.href;
                    //const redirectUri = `${window.location.origin}/auth-callback.html`;

                    console.log("生成授权URL，当前页面: {CurrentUrl}", currentUrl);

                    const response = await fetch(`${this.apiBaseUrl}/auth/auth-url?returnUrl=${encodeURIComponent(currentUrl)}`, {
                        credentials: 'include',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        }
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`获取授权URL失败: ${response.status}, ${errorText}`);
                    }

                    const result = await response.json();

                    if (result.url) {
                        console.log("跳转到微信授权页面: {AuthUrl}", result.url);
                        // 使用页面跳转而不是fetch
                        window.location.href = result.url;
                    } else {
                        this.showApiResult('获取授权URL失败', 'error');
                    }
                } catch (error) {
                    console.error('跳转授权失败:', error);
                    this.showApiResult('跳转授权失败: ' + error.message, 'error');
                }
            }



            startSessionTimer() {
                let timeLeft = this.sessionExpiry / 1000;

                this.sessionTimer = setInterval(() => {
                    timeLeft--;

                    if (timeLeft <= 0) {
                        clearInterval(this.sessionTimer);
                        this.showApiResult('会话已过期', 'warning');
                        this.checkAuthStatus();
                        return;
                    }

                    const minutes = Math.floor(timeLeft / 60);
                    const seconds = timeLeft % 60;
                    document.getElementById('sessionTime').textContent =
                        `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

                    // 最后5分钟显示警告
                    if (timeLeft <= 300) {
                        document.getElementById('sessionTimer').style.background = '#dc3545';
                    } else if (timeLeft <= 600) {
                        document.getElementById('sessionTimer').style.background = '#ffc107';
                        document.getElementById('sessionTimer').style.color = '#000';
                    }

                }, 1000);
            }

            // 调用受保护的API
            async callProtectedApi(endpoint, options = {}) {
                try {
                    const response = await fetch(`${this.apiBaseUrl}${endpoint}`, {
                        credentials: 'include',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            ...options.headers
                        },
                        ...options
                    });

                    if (response.status === 401) {
                        const errorData = await response.json();
                        this.showApiResult('会话已过期，请重新授权', 'warning');
                        this.showAuthModal();
                        return null;
                    }

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    return await response.json();
                } catch (error) {
                    console.error(`API调用失败: ${endpoint}`, error);
                    this.showApiResult('API调用失败: ' + error.message, 'error');
                    return null;
                }
            }

            // 退出登录
            async logout() {
                try {
                    await this.callProtectedApi('/auth/logout', { method: 'POST' });

                    sessionStorage.removeItem('user_info');
                    if (this.sessionTimer) {
                        clearInterval(this.sessionTimer);
                    }
                    window.location.reload();
                } catch (error) {
                    console.error('退出失败:', error);
                    this.showApiResult('退出失败: ' + error.message, 'error');
                }
            }

            // 显示API调用结果
            showApiResult(message, type = 'info') {
                const resultDiv = document.getElementById('apiResult');
                const messageText = typeof message === 'string' ? message : JSON.stringify(message, null, 2);

                resultDiv.innerHTML = `
                        <strong>${this.getTypeText(type)}:</strong>
                        <pre>${messageText}</pre>
                    `;

                resultDiv.className = 'api-result';
                resultDiv.classList.add(type);

                resultDiv.classList.remove('hidden');

                // 5秒后自动隐藏成功和信息消息
                if (type !== 'error') {
                    setTimeout(() => {
                        resultDiv.classList.add('hidden');
                    }, 5000);
                }
            }

            getTypeText(type) {
                const typeMap = {
                    'error': '错误',
                    'success': '成功',
                    'warning': '警告',
                    'info': '信息'
                };
                return typeMap[type] || '信息';
            }
        }

        // 创建认证管理器实例
        const authManager = new AuthManager();

        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            authManager.init();
        });

        // 全局函数供HTML调用
        async function getUserInfo() {
            const result = await authManager.callProtectedApi('/protected/user-info');
            if (result) {
                authManager.showApiResult(result, 'success');

                // 更新用户信息显示
                if (result.nickName) {
                    document.getElementById('userName').textContent = result.nickName;
                    if (result.avatar) {
                        document.getElementById('userAvatar').src = result.avatar;
                        document.getElementById('userAvatar').style.display = 'block';
                    }
                }
            }
        }

        async function getProtectedData() {
            const result = await authManager.callProtectedApi('/protected/data');
            if (result) {
                authManager.showApiResult(result, 'success');
            }
        }

        async function refreshSession() {
            const result = await authManager.callProtectedApi('/auth/refresh-session', {
                method: 'POST'
            });
            if (result) {
                authManager.showApiResult(result.message, 'success');
                // 重置计时器
                if (authManager.sessionTimer) {
                    clearInterval(authManager.sessionTimer);
                }
                authManager.startSessionTimer();
            }
        }

        async function checkSession() {
            await authManager.checkAuthStatus();
            authManager.showApiResult('会话状态检查完成', 'info');
        }

        function logout() {
            if (confirm('确定要退出登录吗？')) {
                authManager.logout();
            }
        }

        function redirectToWeChatAuth() {
            authManager.redirectToWeChatAuth();
        }

        function hideAuthModal() {
            authManager.hideAuthModal();
        }


        function test() {
            // authManager.checkAuthStatus();

            //console.log("hasWeixinCookie:" + hasWeixinCookie());


            //// 检查所有 Cookie
            //console.log('所有 Cookie:', document.cookie);
            //// 运行调试
            //debugCookies();

            //localStorage.setItem('user_info', JSON.stringify("abc"));



           // const data = localStorage.getItem('user_info');
            //console.log("---data:" + data);


        }



       


        // 检查特定 Cookie
        function debugCookies() {
            console.log('=== Cookie 调试信息 ===');
            console.log('所有 Cookie:', document.cookie);
            console.log('Cookie 长度:', document.cookie.length);
            console.log('包含 ltweixin_session:', document.cookie.includes('ltweixin_session'));
            console.log('包含 ltweixin:', document.cookie.includes('ltweixin'));

            // 解析所有 Cookie
            const cookies = document.cookie.split(';');
            console.log('Cookie 列表:', cookies);

            cookies.forEach(cookie => {
                const [name, value] = cookie.trim().split('=');
                console.log(`Cookie: ${name} = ${value}`);
            });
        }

      









        function hasWeixinCookie() {
            return document.cookie.includes('ltweixin_session=');
        }

        // 处理页面可见性变化
        document.addEventListener('visibilitychange', function () {
            if (!document.hidden) {
                authManager.checkAuthStatus();
            }
        });
    </script>
</body>
</html>